package com.tsf.demo.tools.service;

import com.tsf.demo.commons.vo.Product;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p><em>Created on 2022/3/3 4:05 下午</em></p>
 *
 * @author fuzhongtang
 * @since 1.0.1
 */
@Service
public class ProductService {


    //最大库存
    @Value("${maxInventory:100}")
    private int maxInventory;
    //内存商品
    private static List<Product> list = new ArrayList<>();
    private static final Product productDefault = new Product("-","商品不存在",0);


    //查询一个商品
    public Product getProduct(String productId)
    {
        if (list.size()==0)
        {
            init();
        }
        for (Product p:list
             ) {
            if (p.getProductId().equals(productId))
            {
                return p;
            }
        }
        return productDefault;
    }

    //查询所有商品
    public List<Product> getList()
    {
        if (list.size()==0)
        {
            init();
        }
        return list;
    }
    //初始化数据
    private void init()
    {
        for (int i = 0; i < 10; i++) {
            Product product = new Product("product-"+i,"productName-"+i,maxInventory);
            list.add(product);
        }
    }

    //入库
    public String inbound(String productId,Integer quantity)
    {
        if (quantity<1)
        {
            return "false 传入数量不合理:"+quantity;//数量不合理
        }

        for (Product p:list
        ) {
            if (p.getProductId().equals(productId))
            {
                //库存不可大于配置值
                if ((quantity+p.getQuantity())> maxInventory)
                {
                    return "false 库存不可大于配置值";
                }
                p.setQuantity(quantity+p.getQuantity());
                return "true";
            }
        }
        //找不到商品
        return "false 找不到商品";
    }

    //出库
    public String outbound(String productId,Integer quantity)
    {

        for (Product p:list
        ) {
            if (p.getProductId().equals(productId))
            {
                //库存不够
                if (p.getQuantity()<quantity)
                {
                    return "false 库存不够";
                }
                p.setQuantity(p.getQuantity()-quantity);
                return "true";
            }
        }
        //找不到商品
        return "false 找不到商品";
    }
}
